/*
 * 23/10/2011 - 01:35
 */
package org.nettyflux.communicator;

import java.io.IOException;

/**
 * @author Victor Williams Stafusa da Silva
 */
public final class ListeningThread {

    private final Thread listenerThread;
    private final Receiver<?> recv;

    private ListeningThread(Receiver<?> recv) {
        this.recv = recv;
        this.listenerThread = new Thread() {
            @Override
            public void run() {
                listen();
            }
        };
    }

    public static ListeningThread create(Receiver<?> recv) {
        ListeningThread listener = new ListeningThread(recv);
        listener.listenerThread.start();
        return listener;
    }

    public void close() throws IOException {
        recv.close();
    }

    public boolean isClosed() {
        return recv.isClosed();
    }

    private void listen() {
        while (!isClosed()) {
            if (Thread.interrupted()) {
                try {
                    recv.close();
                } catch (IOException e) {
                    // Ignore.
                }
                return;
            }
            try {
                recv.receive();
            } catch (Exception e) {
                // Ignore.
            }
        }
    }
}
